package com.lk.sys.common.aspect;

import com.lk.sys.common.annotation.ClearCache;
import com.lk.sys.common.annotation.RequiredCache;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Aspect
public class SysCacheAscept {

    private Map<Object, Object> cache = new ConcurrentHashMap<>();

    @Pointcut("@annotation(com.lk.sys.common.annotation.RequiredCache)")
    public void doCache() {
    }
    @Pointcut("@annotation(com.lk.sys.common.annotation.ClearCache)")
    public void doClear() {
    }

    //在执行目标方法后，织入清理缓存的功能
    @AfterReturning("doClear()")
    public void doAfterReturning(JoinPoint jp) throws NoSuchMethodException {
        //获取目标方法对西那个
        Class<?> targetCls = jp.getTarget().getClass();
        //获取目标方法的签名，来获取目标方法的名称和参数
        MethodSignature ms = (MethodSignature) jp.getSignature();
        //获取目标方法
        Method targetMethod = targetCls.getDeclaredMethod(ms.getName(), ms.getParameterTypes());
        //获取目标方法的注解
        ClearCache clearCache = targetMethod.getAnnotation(ClearCache.class);
        //获取注解的value
        String key = clearCache.key();
        //移除key对应的缓存
        cache.remove(key);
    }
    //在执行目标方法过程中，织入缓存功能
    @Around("doCache()")
    public Object doAround(ProceedingJoinPoint JP) throws Throwable {
        //获取目标方法对象
        Class<?> targetCls = JP.getTarget().getClass();
        //获取目标方法的签名，来获取目标方法的名字和类型
        MethodSignature ms = (MethodSignature) JP.getSignature();
        //获取目标方法
        Method targetMethod = targetCls.getDeclaredMethod(ms.getName(), ms.getParameterTypes());
        //获取目标方法的注解
        RequiredCache requiredCache = targetMethod.getAnnotation(RequiredCache.class);
        //获取注解的key
        String key = requiredCache.key();
        Object result = cache.get(key);
        if (result != null){
            System.out.println("Get data from cache");
            return result;
        }
        System.out.println("Get data from database");
        result = JP.proceed();
        System.out.println("Put data into cache");
        cache.put(key, result);
        return result;
    }
}
